package cn.hanna.springcloud.service.impl;

import ch.qos.logback.core.util.TimeUtil;
import cn.hanna.springcloud.service.PaymentHystrixService;
import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author smileha
 * @create 2021-10-17 19:14
 * @description
 */
@Service
public class PaymentHystrixServiceImpl implements PaymentHystrixService {

    // ========================服务降级==============================
    @Override
    public String paymentInfo_OK(Integer id) {
        return "访问成功，线程名称："+Thread.currentThread().getName()+",id:"+id;
    }

    @HystrixCommand(fallbackMethod = "paymentInfoException",commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")
    })
    @Override
    public String paymentInfo_TimeOut(Integer id) {
//        int i = 10/0;
        int time = 3;
        try {
            TimeUnit.SECONDS.sleep(time);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "访问成功，线程名称："+Thread.currentThread().getName()+",id:"+id+",总耗时："+time+"秒";
    }

    public String paymentInfoException(Integer id) {
        return "访问成功，线程名称："+Thread.currentThread().getName()+",id:"+id+",出错啦,超时或程序运行异常/(ㄒoㄒ)/~~~~~~~~";
    }



    //================================服务熔断====================================
    @Override
    public String paymentCircuitInfo_OK(Integer id) {
        return "访问成功，线程名称："+Thread.currentThread().getName()+",id:"+id;
    }

    @HystrixCommand(fallbackMethod = "paymentInfoCircuitBreaker",commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled",value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold",value = "1"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds",value = "30000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage",value = "100")

    })
    @Override
    public String paymentCircuitInfo_TimeOut(Integer id) {
        if(id < 0){
            throw new RuntimeException("id不能为负数");
        }
        String uuid = IdUtil.simpleUUID();
        return "访问成功，id:"+id+",流水号："+uuid;
    }

    public String paymentInfoCircuitBreaker(Integer id) {
        return "id:"+ id +"出错啦/(ㄒoㄒ)/~~~~~~~~";
    }
}
